// 引入express，并获得express的实例
const express = require("express");
const path = require("path");
const app = express();
// const axios = require("axios");
const http = require("http");
// 当前所有的客服列表
const userServiceList = require("./store/serviceUsersList.json");
const robotReply = require("./store/robotReply.json");
const e = require("express");

// 用http模块创建一个服务并把express的实例挂载上去
const server = http.Server(app);
// 引入socket.io并立即实例化，把server挂载上去
const io = require("socket.io")(server, { cors: true });

// 记录所有已经登录的用户列表
let users = [];
// 记录登录的客服列表
let currentSeviceUsers = [];
// 随机生成指定范围数字
function randomNum (minNum, maxNum) {
    switch (arguments.length) {
        case 1:
            return parseInt(Math.random() * minNum + 1, 10);
        case 2:
            return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
        default:
            return 0;
    }
}
// app.use("/chatroom", express.static(path.join(__dirname, "/chatroom")));
io.on("connection", (socket) => {
    // 发送消息
    socket.on("sendMsg", (data) => {
        data.State = 1;
        // 向socket触发reviceMsg
        console.log(111111111, data);
        io.to(data.OutTradeNo).emit("reviceMsg", data);
        // socket.emit("changOrShowMsg", data);
    });
    //修改信息阅读状态
    socket.on("changeMsgRead", (data) => {
        users.map((x) => {
            if (x.OutTradeNo === data) {
                x.UnRead = 0;
                x.IsSelect = true;
                return x;
            } else {
                x.IsSelect = false;
                return x;
            }
        });
    });
    // 加入聊天
    socket.on("joinChat", (data) => {
        let serviceList = null;
        let index = 0;
        // 如果发送消息的不是客服
        if (!data.IsService) {
            // 当前登录的客服列表的人数
            let serviceCount = currentSeviceUsers.length;
            // 如果当前登录的客服数量大于0并且每个客服已经达到的最大的服务用户数量
            if (serviceCount > 5) {
                socket.emit("joinError", {
                    msg: "当前咨询人数较多，请稍后再试",
                });
                return;
                // 还有剩余客服
            } else {
                
                // 随机分配客服
                // index = randomNum(0, serviceCount);
                if (!currentSeviceUsers.length) return
                socket.emit("joinSuccess", {
                    ReviceName: currentSeviceUsers[0].SendName,
                    ReviceId: currentSeviceUsers[0].SendId,
                    ReviceOutTradeNo: currentSeviceUsers[0].OutTradeNo,
                });
                io.to(currentSeviceUsers[0].OutTradeNo).emit("connectUserSuccess", {
                    SendName: currentSeviceUsers[0].SendName,
                    SendId: currentSeviceUsers[0].SendId,
                    OutTradeNo: socket.id,
                });
                console.log('joinSuccess1', data, currentSeviceUsers[0]);
                // 让会员加入房间ee
                // socket.join(currentSeviceUsers[0].OutTradeNo);
                // 如果没有客服在线，则返回暂无客服在线
            }
        } else {
            // 如果发送消息的是客服，则加入到聊天室里边
            socket.join(socket.id);
            let serviceUser;

            userServiceList.forEach((item) => {
                if (item.id === data.SendId) {
                    serviceUser = item;
                    return;
                }
            });
            currentSeviceUsers.forEach((item, index) => {
                if (item.SendId === data.SendId) {
                    currentSeviceUsers.splice(index, 1);
                }
            });
            if (serviceUser.id >= 0) {
                let user = {
                    SendId: serviceUser.id,
                    SendName: serviceUser.SendName,
                    ReviceId: serviceList ? serviceList[index].SendId : data.ReviceId,
                    ReviceName: serviceList
                        ? serviceList[index].SendName
                        : data.ReviceName,
                    NoCode: data.NoCode,
                    OutTradeNo: socket.id,
                    Room: data.IsService ? socket.io : serviceList[index].OutTradeNo,
                    IsService: serviceUser.IsService,
                    IsSelect: false,
                    SessionContent: serviceUser.SendName + "加入会话",
                    UnRead: 0,
                    CloseSession: false,
                };
                currentSeviceUsers.push(user);
                socket.emit("joinSuccess", user);
            } else {
                socket.emit("joinError", `已经加入了${socket.id}`);
            }
        }
        // 把登录成功的sendId记录下来
        socket.SendId = data.SendId;
    });

    // 客服手动离线
    socket.on("offLine", (data) => {
        //把客服和会员从users列表中删除
        users = users.filter(
            (x) => x.OutTradeNo != socket.io && x.ReviceId != data.SendId
        );
        io.emit("offSuccess", {
            Users: users,
            SendId: data.SendId,
            NoCode: data.NoCode,
        });
    });
    //客服关闭会话
    socket.on("closeSeesion", (data) => {
        //将该会员从users列表删除
        users = users.filter((x) => x.SendId != data.SendId);
        socket.to(data.OutTradeNo).emit("closeSessionSuccess", {
            Users: users,
            SendId: data.SendId,
        });
        socket.emit("closeSessionSuccess", {
            Users: users,
            SendId: data.SendId,
        });
    });
    // 用户断开连接的功能
    socket.on("disconnect", () => {
        //获取客服房间的OutTradeNo
        let serviceOutTradeNo = "";
        let user = users.filter((x) => x.OutTradeNo === socket.id);
        if (user.length > 0) {
            if (!user[0].IsService) {
                serviceOutTradeNo = users.filter(
                    (x) => x.SendId === user[0].ReviceId
                )[0].OutTradeNo;
            } else {
                serviceOutTradeNo = user[0].OutTradeNo;
            }
        }
        //将该会员从users列表删除
        if (socket.SendId && socket.SendId > 0) {
            users = users.filter(
                (x) => x.OutTradeNo != socket.id && x.ReviceId != socket.SendId
            );
        }
        // 会员离线
        if (user.length > 0 && !user[0].IsService && serviceOutTradeNo) {
            socket.to(serviceOutTradeNo).emit("customerDisconnect", {
                SendId: socket.SendId,
                Users: users,
            });
        }
        // 客服离线
        else if (user.length > 0 && user[0].IsService && serviceOutTradeNo) {
            io.in(serviceOutTradeNo).emit("serviceDisconnect", {
                SendId: socket.SendId,
                Users: users,
            });
        }
    });
});

server.listen(3199, function () {
    console.log("服务端启动成功！端口3199");
});
